import os
from odoo import fields, models, api
from odoo.exceptions import UserError


class DocumentUploadWizard(models.TransientModel):
    _name = 'document.upload.wizard'
    _description = 'Document Upload Wizard'

    res_model = fields.Char(string='Model', required=True)
    res_id = fields.Integer(string='Record ID', required=True, default=lambda self: self.env.context.get('default_res_id'))

    # Modified to Many2many to support multiple file uploads.
    # ir.attachment already holds file data (datas) and filename (name).
    attachment_ids = fields.Many2many(
        'ir.attachment',
        string='Files to Upload',
        required=True,
        help="Select multiple files to upload to the document management system."
    )

    partner_id = fields.Many2one('res.partner', string='Partner', default=lambda self: self.env.context.get('default_partner_id'))
    tag_id = fields.Many2one(
        'documents.tag',
        string='Document Type',
        required=True,
        domain="[('folder_id', '=', folder_id)]",
        default=lambda self: self.env.context.get('default_tag_id', False)
    )
    folder_id = fields.Many2one(
        'documents.folder',
        string='Folder',
        default=lambda self: self.env.context.get('default_folder_id')
    )

    @api.onchange('res_model', 'res_id')
    def _onchange_res_record(self):
        """
        Dynamically sets folder_id if context provides relevant information
        and folder_id is not already set.
        This is useful when opening the wizard from a documents.folder view.
        """
        if not self.folder_id and self.env.context.get('active_model') == 'documents.folder' and self.env.context.get('active_id'):
            self.folder_id = self.env.context.get('active_id')

    @api.onchange('folder_id')
    def _onchange_folder_id(self):
        """
        Resets the document type when the folder changes to ensure the
        selected tag belongs to the new folder's domain.
        """
        if self.tag_id and self.tag_id.folder_id != self.folder_id:
            self.tag_id = False

    def action_upload(self):
        """
        Uploads the selected multiple files as documents.document records.
        Each file will be converted into a new document.
        """
        self.ensure_one()

        if not self.attachment_ids:
            raise UserError("Please select files to upload.")

        documents_to_create = []
        related_record_name = ""

        # Attempt to get the name of the related record for document naming.
        # Fallback to a default name if the record doesn't exist or has no 'name' field.
        if self.res_model and self.res_id:
            related_record = self.env[self.res_model].browse(self.res_id)
            if related_record.exists() and hasattr(related_record, 'name'):
                related_record_name = related_record.name
            elif related_record.exists() and related_record._rec_name:
                # Fallback to display_name or _rec_name value
                related_record_name = related_record.display_name
            else:
                related_record_name = f"Record_{self.res_model}_{self.res_id}"
        else:
            related_record_name = "Unnamed_Record"

        for attachment in self.attachment_ids:
            # ir.attachment's 'name' field holds the original filename, and 'datas' holds the binary data.
            original_filename = attachment.name
            file_extension = os.path.splitext(original_filename)[1] if original_filename else ''
            file_prefix = os.path.splitext(original_filename)[0] if original_filename else ''

            # Construct the new document name: related_record_name-original_file_prefix.extension
            new_document_name = f"{related_record_name}-{file_prefix}{file_extension}"

            documents_to_create.append({
                'name': new_document_name,
                'datas': attachment.datas,  # Get binary data directly from ir.attachment
                'res_model': self.res_model,
                'res_id': self.res_id,
                'partner_id': self.partner_id.id if self.partner_id else False,  # Ensure ID is passed, handle False
                'folder_id': self.folder_id.id,
                'tag_ids': [(4, self.tag_id.id)],  # Link the selected tag
                'is_locked': True,  # Lock the document upon creation
                'lock_uid': self.env.user.id  # Lock by current user
            })

        # Batch create all document records for efficiency
        if documents_to_create:
            self.env['documents.document'].create(documents_to_create)

        # Close the wizard after successful upload
        return {'type': 'ir.actions.act_window_close'}
